package com.fbt.transfer.app.driver.view;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;

import androidx.annotation.ColorInt;
import androidx.annotation.Nullable;

import com.fbt.transfer.app.driver.R;

/**
 * 自定义滑动控件
 * 从左到右滑动时，滑过的区域变为自定义颜色
 * 支持自定义文字内容、文字样式、滑块背景色、滑动路径颜色等
 */
public class SlideToView extends View {

    private static final int DEFAULT_THUMB_SIZE_DP = 56; // 修改为与轨道高度一致
    private static final int DEFAULT_TRACK_HEIGHT_DP = 56;
    private static final int DEFAULT_TRACK_PADDING_DP = 0; // 移除内边距
    private static final int DEFAULT_TEXT_SIZE_SP = 16;
    private static final int DEFAULT_TRACK_COLOR = Color.LTGRAY;
    private static final int DEFAULT_TRACK_FILLED_COLOR = Color.GREEN;
    private static final int DEFAULT_THUMB_COLOR = Color.WHITE;
    private static final int DEFAULT_TEXT_COLOR = Color.DKGRAY;
    private static final int ANIMATION_DURATION = 200;
    private static final float DEFAULT_SLIDE_THRESHOLD = 0.9f; // 滑动超过90%触发事件
    
    // 滑块形状类型
    public static final int SHAPE_CIRCLE = 0;
    public static final int SHAPE_ROUNDED_RECT = 1;

    private Paint mTrackPaint;
    private Paint mTrackFilledPaint;
    private Paint mThumbPaint;
    private Paint mTextPaint;
    private Paint mArrowPaint; // 箭头画笔

    private float mThumbX;
    private float mThumbRadius;
    private float mTrackHeight;
    private float mTrackPadding;
    private float mTrackWidth;
    private RectF mTrackRectF;
    private RectF mTrackFilledRectF;
    private RectF mThumbRectF;
    private boolean mIsSliding = false;
    private float mSlideThreshold = DEFAULT_SLIDE_THRESHOLD; // 滑动超过90%触发事件
    private boolean mHasCompleted = false;
    private String mText = "滑动解锁";
    private Rect mTextBounds = new Rect();
    private OnSlideCompleteListener mListener;
    private ValueAnimator mResetAnimator;
    
    // 新增属性
    private int mThumbShape = SHAPE_CIRCLE;
    private boolean mTextBold = false;
    private String mCompletedText = null; // 滑动完成后显示的文字，为null则不显示文字
    private OnSlideStartListener mStartListener;
    private OnSlideProgressListener mProgressListener;
    private float mLastX; // 添加记录上一次触摸位置的变量
    private float mTouchOffset; // 记录手指按下时与滑块左边的偏移

    public interface OnSlideCompleteListener {
        void onSlideComplete();
    }

    public interface OnSlideStartListener {
        void onSlideStart();
    }
    
    public interface OnSlideProgressListener {
        void onSlideProgress(float progress);
    }

    public SlideToView (Context context) {
        this(context, null);
    }

    public SlideToView (Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SlideToView (Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        float density = context.getResources().getDisplayMetrics().density;
        float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;

        mThumbRadius = DEFAULT_THUMB_SIZE_DP * density / 2;
        mTrackHeight = DEFAULT_TRACK_HEIGHT_DP * density;
        mTrackPadding = DEFAULT_TRACK_PADDING_DP * density;
        float textSize = DEFAULT_TEXT_SIZE_SP * scaledDensity;
        int trackColor = DEFAULT_TRACK_COLOR;
        int trackFilledColor = DEFAULT_TRACK_FILLED_COLOR;
        int thumbColor = DEFAULT_THUMB_COLOR;
        int textColor = DEFAULT_TEXT_COLOR;

        if (attrs != null) {
            TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SlideToNavigateView);
            mText = a.getString(R.styleable.SlideToNavigateView_slideText) != null ?
                    a.getString(R.styleable.SlideToNavigateView_slideText) : mText;
            mThumbRadius = a.getDimension(R.styleable.SlideToNavigateView_thumbSize, mThumbRadius);
            mTrackHeight = a.getDimension(R.styleable.SlideToNavigateView_trackHeight, mTrackHeight);
            textSize = a.getDimension(R.styleable.SlideToNavigateView_textSize, textSize);
            trackColor = a.getColor(R.styleable.SlideToNavigateView_trackColor, trackColor);
            trackFilledColor = a.getColor(R.styleable.SlideToNavigateView_trackFilledColor, trackFilledColor);
            thumbColor = a.getColor(R.styleable.SlideToNavigateView_thumbColor, thumbColor);
            textColor = a.getColor(R.styleable.SlideToNavigateView_textColor, textColor);
            
            // 读取新增的自定义属性
            mThumbShape = a.getInt(R.styleable.SlideToNavigateView_thumbShape, SHAPE_CIRCLE);
            mTextBold = a.getBoolean(R.styleable.SlideToNavigateView_textBold, false);
            mCompletedText = a.getString(R.styleable.SlideToNavigateView_completedText);
            float threshold = a.getFloat(R.styleable.SlideToNavigateView_slideThreshold, mSlideThreshold);
            if (threshold > 0 && threshold <= 1) {
                mSlideThreshold = threshold;
            }
            
            a.recycle();
        }
        
        // 初始化滑块矩形区域
        mThumbRectF = new RectF();

        // 初始化画笔
        mTrackPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mTrackPaint.setColor(trackColor);
        mTrackPaint.setStyle(Paint.Style.FILL);

        mTrackFilledPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mTrackFilledPaint.setColor(trackFilledColor);
        mTrackFilledPaint.setStyle(Paint.Style.FILL);

        mThumbPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mThumbPaint.setColor(thumbColor);
        mThumbPaint.setStyle(Paint.Style.FILL);

        mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mTextPaint.setColor(textColor);
        mTextPaint.setTextSize(textSize);
        mTextPaint.setTextAlign(Paint.Align.CENTER);
        if (mTextBold) {
            mTextPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
        }

        mTrackRectF = new RectF();
        mTrackFilledRectF = new RectF();

        // 初始化重置动画
        mResetAnimator = new ValueAnimator();
        mResetAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
        mResetAnimator.setDuration(ANIMATION_DURATION);
        mResetAnimator.addUpdateListener(animation -> {
            mThumbX = (float) animation.getAnimatedValue();
            updateTrackFilledRect();
            invalidate();
        });

        // 初始化箭头画笔
        mArrowPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mArrowPaint.setColor(textColor);
        mArrowPaint.setStyle(Paint.Style.FILL);
        mArrowPaint.setTextSize(textSize * 1.2f); // 箭头文字稍大一些
        mArrowPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
        mArrowPaint.setTextAlign(Paint.Align.CENTER);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int minWidth = (int) (mThumbRadius * 4);
        int minHeight = (int) (mTrackHeight + getPaddingTop() + getPaddingBottom());

        int width = resolveSize(minWidth, widthMeasureSpec);
        int height = resolveSize(minHeight, heightMeasureSpec);

        setMeasuredDimension(width, height);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

        mTrackWidth = w - getPaddingLeft() - getPaddingRight();
        float trackLeft = getPaddingLeft();
        float trackTop = getPaddingTop() + (h - getPaddingTop() - getPaddingBottom() - mTrackHeight) / 2;
        float trackRight = w - getPaddingRight();
        float trackBottom = trackTop + mTrackHeight;

        mTrackRectF.set(trackLeft, trackTop, trackRight, trackBottom);
        mThumbX = trackLeft; // 滑块左边与轨道左边贴合
        updateTrackFilledRect();
    }

    private void updateTrackFilledRect() {
        // 使用轨道高度作为滑块宽度
        float thumbWidth = mTrackHeight;
        mTrackFilledRectF.set(
                mTrackRectF.left,
                mTrackRectF.top,
                mThumbX + thumbWidth,
                mTrackRectF.bottom
        );
        
        // 更新滑块矩形区域
        if (mThumbShape == SHAPE_ROUNDED_RECT) {
            mThumbRectF.set(
                    mThumbX,
                    mTrackRectF.top,
                    mThumbX + thumbWidth,
                    mTrackRectF.bottom
            );
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        // 绘制轨道背景
        canvas.drawRoundRect(mTrackRectF, mTrackHeight / 2, mTrackHeight / 2, mTrackPaint);

        // 绘制已滑过的轨道
        if (mThumbX > mTrackRectF.left) {
            canvas.drawRoundRect(mTrackFilledRectF, mTrackHeight / 2, mTrackHeight / 2, mTrackFilledPaint);
        }

        // 绘制滑块
        if (mThumbShape == SHAPE_CIRCLE) {
            // 对于圆形滑块，使用轨道高度作为直径
            float thumbDiameter = mTrackHeight;
            float centerX = mThumbX + thumbDiameter / 2;
            canvas.drawCircle(centerX, mTrackRectF.centerY(), thumbDiameter / 2, mThumbPaint);
        } else {
            // 使滑块与轨道形状一致，高度相同
            mThumbRectF.set(
                mThumbX,
                mTrackRectF.top,
                mThumbX + mTrackHeight, // 使用轨道高度作为宽度，保持正方形
                mTrackRectF.bottom
            );
            canvas.drawRoundRect(mThumbRectF, mTrackHeight / 2, mTrackHeight / 2, mThumbPaint);
        }

        // 绘制文本
        if (mHasCompleted && mCompletedText != null) {
            mTextPaint.getTextBounds(mCompletedText, 0, mCompletedText.length(), mTextBounds);
            float textX = mTrackRectF.centerX();
            float textY = mTrackRectF.centerY() + (mTextBounds.height() / 2f);
            canvas.drawText(mCompletedText, textX, textY, mTextPaint);
        } else if (!mHasCompleted) {
            mTextPaint.getTextBounds(mText, 0, mText.length(), mTextBounds);
            float textX = mTrackRectF.centerX();
            float textY = mTrackRectF.centerY() + (mTextBounds.height() / 2f);
            canvas.drawText(mText, textX, textY, mTextPaint);
        }

        // 绘制箭头
        if (!mHasCompleted) {
            float arrowX = mThumbX + mThumbRadius;
            float arrowY = mTrackRectF.centerY() + (mTextBounds.height() / 2f);
            canvas.drawText(">>", arrowX, arrowY, mArrowPaint);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mHasCompleted) {
            return false;
        }

        float x = event.getX();
        float y = event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (isThumbTouched(x, y)) {
                    mIsSliding = true;
                    mLastX = x;
                    // 记录手指与滑块左边的偏移
                    mTouchOffset = x - mThumbX;
                    if (mStartListener != null) {
                        mStartListener.onSlideStart();
                    }
                    return true;
                }
                break;

            case MotionEvent.ACTION_MOVE:
                if (mIsSliding) {
                    // 滑块左边 = 当前手指位置 - 按下时的偏移
                    float newThumbX = x - mTouchOffset;
                    // 限制在有效范围内，使用轨道高度作为滑块宽度
                    float thumbWidth = mTrackHeight;
                    newThumbX = Math.max(mTrackRectF.left, Math.min(newThumbX, mTrackRectF.right - thumbWidth));
                    mThumbX = newThumbX;
                    updateTrackFilledRect();
                    
                    // 计算并通知滑动进度
                    if (mProgressListener != null) {
                        float progress = (mThumbX - mTrackRectF.left) /
                                (mTrackRectF.width() - thumbWidth);
                        mProgressListener.onSlideProgress(progress);
                    }
                    invalidate();
                    return true;
                }
                break;

            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                if (mIsSliding) {
                    mIsSliding = false;
                    float thumbWidth = mTrackHeight;
                    float slidePercent = (mThumbX - mTrackRectF.left) /
                            (mTrackRectF.width() - thumbWidth);
                    if (slidePercent > mSlideThreshold) {
                        // 滑动到最右侧，确保滑块右边与轨道右边对齐
                        ValueAnimator completeAnimator = ValueAnimator.ofFloat(mThumbX, mTrackRectF.right - thumbWidth);
                        completeAnimator.setDuration(ANIMATION_DURATION);
                        completeAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
                        completeAnimator.addUpdateListener(animation -> {
                            mThumbX = (float) animation.getAnimatedValue();
                            updateTrackFilledRect();
                            invalidate();
                        });
                        completeAnimator.addListener(new android.animation.AnimatorListenerAdapter() {
                            @Override
                            public void onAnimationEnd(android.animation.Animator animation) {
                                mHasCompleted = true;
                                if (mListener != null) {
                                    mListener.onSlideComplete();
                                }
                            }
                        });
                        completeAnimator.start();
                    } else {
                        resetThumb();
                    }
                    return true;
                }
                break;
        }
        return super.onTouchEvent(event);
    }

    private boolean isThumbTouched(float x, float y) {
        if (mThumbShape == SHAPE_CIRCLE) {
            // 对于圆形滑块，使用轨道高度作为直径
            float thumbDiameter = mTrackHeight;
            float centerX = mThumbX + thumbDiameter / 2;
            float distance = (float) Math.sqrt(Math.pow(x - centerX, 2) + Math.pow(y - mTrackRectF.centerY(), 2));
            return distance <= thumbDiameter / 2;
        } else {
            // 更新滑块矩形区域以确保触摸检测准确
            mThumbRectF.set(
                mThumbX,
                mTrackRectF.top,
                mThumbX + mTrackHeight, // 使用轨道高度作为宽度
                mTrackRectF.bottom
            );
            return mThumbRectF.contains(x, y);
        }
    }

    private void resetThumb() {
        mResetAnimator.cancel();
        mResetAnimator.setFloatValues(mThumbX, mTrackRectF.left); // 重置到轨道左边
        mResetAnimator.setDuration(ANIMATION_DURATION);
        mResetAnimator.start();
    }

    public void reset() {
        mHasCompleted = false;
        resetThumb();
    }

    public void setOnSlideCompleteListener(OnSlideCompleteListener listener) {
        mListener = listener;
    }

    public void setOnSlideStartListener(OnSlideStartListener listener) {
        mStartListener = listener;
    }
    
    public void setOnSlideProgressListener(OnSlideProgressListener listener) {
        mProgressListener = listener;
    }

    /**
     * 设置滑块文本
     * @param text 文本内容
     */
    public void setText(String text) {
        mText = text;
        invalidate();
    }
    
    /**
     * 设置滑动完成后显示的文本
     * @param text 完成后的文本，null表示不显示文本
     */
    public void setCompletedText(String text) {
        mCompletedText = text;
        invalidate();
    }

    /**
     * 设置轨道背景颜色
     * @param color 颜色值
     */
    public void setTrackColor(@ColorInt int color) {
        mTrackPaint.setColor(color);
        invalidate();
    }

    /**
     * 设置已滑过轨道的颜色
     * @param color 颜色值
     */
    public void setTrackFilledColor(@ColorInt int color) {
        mTrackFilledPaint.setColor(color);
        invalidate();
    }

    /**
     * 设置滑块颜色
     * @param color 颜色值
     */
    public void setThumbColor(@ColorInt int color) {
        mThumbPaint.setColor(color);
        invalidate();
    }

    /**
     * 设置文本颜色
     * @param color 颜色值
     */
    public void setTextColor(@ColorInt int color) {
        mTextPaint.setColor(color);
        invalidate();
    }
    
    /**
     * 设置文本是否加粗
     * @param bold 是否加粗
     */
    public void setTextBold(boolean bold) {
        mTextBold = bold;
        if (bold) {
            mTextPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
        } else {
            mTextPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.NORMAL));
        }
        invalidate();
    }
    
    /**
     * 设置文本大小
     * @param sizeSp 文本大小，单位sp
     */
    public void setTextSize(float sizeSp) {
        float scaledDensity = getContext().getResources().getDisplayMetrics().scaledDensity;
        mTextPaint.setTextSize(sizeSp * scaledDensity);
        invalidate();
    }
    
    /**
     * 设置滑块形状
     * @param shape 形状类型，{@link #SHAPE_CIRCLE} 或 {@link #SHAPE_ROUNDED_RECT}
     */
    public void setThumbShape(int shape) {
        if (shape != SHAPE_CIRCLE && shape != SHAPE_ROUNDED_RECT) {
            throw new IllegalArgumentException("Shape must be SHAPE_CIRCLE or SHAPE_ROUNDED_RECT");
        }
        mThumbShape = shape;
        updateTrackFilledRect();
        invalidate();
    }
    
    /**
     * 设置滑动阈值，即滑动超过多少比例触发完成事件
     * @param threshold 阈值，范围0-1，默认0.9
     */
    public void setSlideThreshold(float threshold) {
        if (threshold < 0 || threshold > 1) {
            throw new IllegalArgumentException("Threshold must be between 0 and 1");
        }
        mSlideThreshold = threshold;
    }
}